package com.hzcx.app.simplechat.ui.publicui;

import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.base.BaseActivity;
import com.hzcx.app.simplechat.base.BaseDialog;
import com.hzcx.app.simplechat.chat.ChatUtil;
import com.hzcx.app.simplechat.chat.constant.ChatConstant;
import com.hzcx.app.simplechat.common.Common;
import com.hzcx.app.simplechat.ui.chat.ChatShareUserActivity;
import com.hzcx.app.simplechat.ui.chat.dialog.ChatShareUserDialog;
import com.hzcx.app.simplechat.ui.chat.event.ChatShareUserEvent;
import com.hzcx.app.simplechat.ui.login.event.WxLoginSuccessEvent;
import com.hzcx.app.simplechat.ui.publicui.bean.ShareInfoBean;
import com.hzcx.app.simplechat.ui.publicui.contract.ShareContract;
import com.hzcx.app.simplechat.ui.publicui.presenter.SharePresenter;
import com.hzcx.app.simplechat.ui.user.bean.UserInfoBean;
import com.hzcx.app.simplechat.util.NavigationBarInfo;
import com.hzcx.app.simplechat.util.app.AppHelper;
import com.hzcx.app.simplechat.util.empty.EmptyUtils;
import com.hzcx.app.simplechat.util.log.LogUtils;
import com.hzcx.app.simplechat.util.toast.ToastUtils;
import com.hzcx.app.simplechat.util.wx.WxShareUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 分享弹窗
 */
public class ShareActivity extends BaseActivity<SharePresenter> implements ShareContract.View {

    public static final String INTENT_USER_ID = "INTENT_USER_ID";

    @BindView(R.id.tv_cancel)
    TextView tvCancel;
    @BindView(R.id.ll_wechat)
    LinearLayout llWechat;
    @BindView(R.id.ll_friend_moment)
    LinearLayout llFriendMoment;

    private int userId;
    private int tag;


    @Override
    public int getLayout() {
        return R.layout.dialog_share;
    }

    @Override
    public void initPresenter() {
        mPresenter = new SharePresenter();
    }

    @Override
    public void initView() {

        // 显示在最底部
        getWindow().setGravity(Gravity.BOTTOM);
        getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        int height= NavigationBarInfo.getNavigationBarHeight(this);
        LogUtils.d("height:"+height);
        if(height<50){
            height=0;
        }
        WindowManager.LayoutParams params=getWindow().getAttributes();
        params.y=height;

        tvCancel.setOnClickListener(view -> finish());


    }

    @Override
    public void initData() {
        userId = getIntent().getIntExtra(INTENT_USER_ID, 0);
    }

    @OnClick({R.id.ll_wechat, R.id.ll_friend_moment, R.id.ll_friend, R.id.ll_copy_url, R.id.ll_slogan_member})
    public void viewOnClick(View view) {
        switch (view.getId()) {
            case R.id.ll_wechat: // 微信好友
                mPresenter.getShareInfo(this, userId, 0);
                break;

            case R.id.ll_friend_moment: // 朋友圈
                mPresenter.getShareInfo(this, userId, 1);
                break;

            case R.id.ll_friend: // 我的好友
                startActivity(new Intent(this, ChatShareUserActivity.class)
                        .putExtra(ChatShareUserActivity.INTENT_FROM_TAG, 3));
                break;

            case R.id.ll_copy_url: // 复制链接
                mPresenter.getShareInfo(this, userId, 2);
                break;

            case R.id.ll_slogan_member: // 获取口令
                mPresenter.getShareInfo(this, userId, 3);
                break;
        }
    }

    /**
     * 分享内容返回
     *
     * @param data
     */
    @Override
    public void shareResult(ShareInfoBean data, int tag) {
        if (tag == 3) {
            AppHelper.copy(this, data.getSlogan_copy());
            showConfirmDialog("复制成功", data.getSlogan_show(), "去粘贴", () -> {
                try {
                    Intent intent = new Intent(Intent.ACTION_MAIN);
                    ComponentName cmp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");
                    intent.addCategory(Intent.CATEGORY_LAUNCHER);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setComponent(cmp);
                    startActivity(intent);
                } catch (ActivityNotFoundException e) {
                    // TODO: handle exception
                    ToastUtils.show("检查到您手机没有安装微信，请安装后使用该功能");
                }
                finish();
            });
            return;
        }
        if (tag == 2) {
            AppHelper.copy(this, data.getShare_url());
            showError("复制成功");
            return;
        }
        showLoading();
        Glide.with(this).asBitmap().load(data.getAvatar()).into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                hideLoading();
                WxShareUtils.shareWeb(ShareActivity.this, Common.WX_APP_ID, data.getShare_url(), data.getTitle(), data.getDescription(), resource, tag);
            }

            @Override
            public void onLoadFailed(@Nullable Drawable errorDrawable) {
                super.onLoadFailed(errorDrawable);
                hideLoading();
                showError("头像下载失败");
            }
        });
    }

    /**
     * 用户信息获取成功
     *
     * @param data
     * @param event
     */
    @Override
    public void userInfoResult(UserInfoBean data, ChatShareUserEvent event) {
        ChatUtil.getInstance().sendShareUserMessage(data.getNickname(), data.getMember_id(), data.getAvatar(), data.getChatnumber(),
                null, event.getBean().getHxusername(), ChatConstant.CHATTYPE_SINGLE, event.getBean().getMember_id()
                , EmptyUtils.isEmpty(event.getBean().getRemarks_name()) ? event.getBean().getNickname() : event.getBean().getRemarks_name(), null);
        showError("分享成功");
        finish();
    }

    /**
     * 微信调用成功
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void wxLoginSuccess(WxLoginSuccessEvent event) {
        if (event.isSuccess()) {
            showError("分享成功");
        } else {
            showError("分享失败");
        }
    }

    /**
     * 分享给好友,选择好友返回
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void shareUser(ChatShareUserEvent event) {
        mPresenter.getUserInfo(this, userId, event);
    }
}
